<template>
  <div class="page">
    <el-tabs v-model="activeName" :before-leave="tabLevel">
      <el-tab-pane label="基础信息" name="1">
        <el-form
          ref="formRef"
          class="form_item_w2"
          :model="pageForm"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="所属学院" prop="collageId">
            <TheDeptSelect v-model="pageForm.collageId" :modelValue="pageForm.collageId" :deptType="39" placeholder="请选择所属学院" :disabled="disabled" @update:modelValue="pageForm.collageId = $event"/>
          </el-form-item>
          <el-form-item label="所属专业" prop="majorId">
            <TheDeptSelect v-model="pageForm.majorId" :modelValue="pageForm.majorId" :deptType="40" placeholder="请选择所属专业"  :disabled="disabled" @update:modelValue="pageForm.majorId = $event"/>
          </el-form-item>
          <el-form-item label="班级名称" prop="classId">
            <TheDeptSelect v-model="pageForm.classId" :modelValue="pageForm.classId" :deptType="41"
                           placeholder="请选择所属班级" :disabled="disabled"
                           @update:modelValue="pageForm.classId = $event"/>
          </el-form-item>
          <el-form-item label="授课教师" prop="teacherName">
            <el-input v-model="pageForm.teacherName" placeholder="请输入授课教师" disabled></el-input>
          </el-form-item>
          <el-form-item label="成绩类型" prop="scoreTypeId">
            <el-select v-model="pageForm.scoreTypeId" placeholder="请输入课程类型" :disabled="disabled">
              <el-option
                v-for="(dictItem,index) in scoreTypeDicts"
                :label="dictItem.dictLabel"
                :value="dictItem.dictCode"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学年" prop="academicYear">
            <el-input v-model="pageForm.academicYear" placeholder="请输入学年" :disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="考试批次" prop="examBatch">
            <el-input v-model="pageForm.examBatch" placeholder="请输入考试批次" :disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="考试时间" prop="examDate">
            <el-date-picker
              v-model="pageForm.examDate"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :disabled="disabled"
              placeholder="请选择考试时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="pageForm.remarks" placeholder="请输入备注" :disabled="disabled"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="成绩信息" name="2">
        <div style="margin-bottom: 20px;">
          <el-button type="primary" @click="batchUploadStudent">批量导入</el-button>
          <el-button type="primary" @click="templateDownload">模板下载</el-button>
        </div>
        <el-table v-if="tableData.length>0" :data="tableData" border style="width: 100%">
          <el-table-column type="index" width="70" align="center"></el-table-column>
          <el-table-column 
            align="center" 
            v-for="header in tableHeaders" 
            :key="header.prop"
            :prop="header.prop" 
            :label="header.label">
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div class="pageFooterBtn">
      <el-button @click="$router.back()">关 闭</el-button>
      <el-button type="primary" @click="handleSubmit()" v-if="['add','edit'].includes(action)" :loading="loading">暂 存
      </el-button>
    </div>
    <TheUploadEGrades ref="TheUploadEGradesRef" @uploadSuccess="uploadSuccess"/>

  </div>
</template>
<script>
import TheTable from '@/componentsView/TheTable.vue';
import {rules} from './data'
import {useDict} from '@/utils/dict/useDict'
import {teachingGradesAddApi, teachingGradesEditApi, teachingGradesByIdApi} from '@/api/teachingIdea/teachingGrades'
import {getInfo} from '@/api/login'
import TheDeptSelect from '@/componentsView/TheDeptSelect.vue';
import TheUploadEGrades from "@/views/teachingIdea/teachingGrades/TheUploadEGrades.vue";

export default {
  name: 'teachingGradesDetail',
  components: {TheUploadEGrades, TheTable, TheDeptSelect},
  data() {
    return {
      rules,
      pageForm: {
        classId: null,
        collageId: null,
      },
      loading: false,
      disabled: false,
      scoreTypeDicts: [],
      scoreId: this.$route.query.scoreId,
      action: this.$route.query.action,
      activeName: '1',
      tableData: [],
      tableHeaders: []
    }
  },

  async created() {
    this.getUserInfo()
    this.scoreTypeDicts = await useDict('score_type')
    if (this.scoreId) this.getById()
  },
  methods: {
    tabLevel(activeName, oldActiveName) {
      if(oldActiveName === '1' && !this.scoreId){
        this.$message.info("请先暂存基本信息")
        return false
      }else{
        return true
      }
    },
    getUserInfo() {
      getInfo().then(res => {
        this.pageForm.teacherId = res.user.userId;
        this.pageForm.teacherName = res.user.userName
      })
    },

    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.loading = true
        let res = {}
        if (this.scoreId) {
          delete this.pageForm.fileInfo
          res = await teachingGradesEditApi(this.pageForm)
        } else {
          res = await teachingGradesAddApi(this.pageForm)
        }
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.scoreId = res.data
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        this.$message.error('操作失败')
      } finally {
        this.loading = false
      }
    },

    uploadSuccess(){
      this.$router.back()
    },
    batchUploadStudent() {
      this.$refs.TheUploadEGradesRef.open(this.scoreId);
    },
    templateDownload() {
      window.open('http://220.154.128.89:9443/statics/2025/09/21/学生成绩_20250921145035A039.xlsx', "_blank")
    },
    async getById() {
      if (this.action === 'look') this.disabled = true
      teachingGradesByIdApi(this.scoreId).then(res => {
        if (res.code === 200) {
          this.pageForm = res.data
          // 处理数据
          this.tableData = this.transformStudentScores(res.data.studentList);
          // 获取动态表头
          this.tableHeaders = this.getTableHeaders(this.tableData);
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 转换函数 - 处理表格数据
    transformStudentScores(students) {
      return students.map(student => {
        const scoreStr = student.studentScore.replace(/[{}]/g, '');
        const scorePairs = scoreStr.split(',');
        const result = {};
        
        scorePairs.forEach(pair => {
          const [subject, score] = pair.trim().split('=');
          result[subject] = Number(score);
        });
        
        return result;
      });
    },

    // 获取动态表头
    getTableHeaders(tableData) {
      // 从第一条数据中提取表头信息
      if (tableData.length === 0) return [];
      return Object.keys(tableData[0]).map(key => ({
        prop: key,       // 对应数据的属性名
        label: key       // 表格显示的标题
      }));
    }
  },
}
</script>
<style scoped lang="scss">
.page {
  padding: 20px;
  margin: 20px !important;
  border-radius: 6px;
  background-color: #FFFFFF;
}

::v-deep .el-select {
  width: 100% !important;
}

::v-deep .el-date-editor {
  width: 100% !important;
}
</style>
